package com.woniuxy.oa.utils;
 
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.woniuxy.oa.entity.Approval;
import com.woniuxy.oa.entity.Employee;
import com.woniuxy.oa.enums.ApprovalApplyType;
import com.woniuxy.oa.exception.ApprovalException;
import com.woniuxy.oa.service.ApprovalService;

@Component
public class ApprovalUtil {

	@Autowired
	private ApprovalService approvalService;

	private static ApprovalService utilApprovalService;

	@PostConstruct
	public void init() {
		utilApprovalService = approvalService;
	}

	// 获取当前时间并返回一个格式化字符串的方法
	public static String getNow() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化时间
		Date date = new Date();// 获取当前时间
		return sdf.format(date);
	}
	
	/**
	 * 插入审批信息并获取审批号
	 * @param request
	 * @param a_eid 审批人，通过下拉框获取并传到后台
	 * @param a_type	审批类型，通过枚举选择
	 * @return	返回插入后的审批号
	 */
	public static Integer addApprovalGetId(HttpServletRequest request, Integer a_eid, ApprovalApplyType a_type) {
		try { 
			Approval approval = new Approval();
			// 审批人id,使用下拉框访问ApprovalController的方法获取
			approval.setA_eid(a_eid);
			//发起人id，整合登录之后根据request获取，这里先写死
//			approval.setE_id(((Employee)request.getSession().getAttribute("user")).getId());
			approval.setE_id(9);
			//当前时间字符串
			approval.setC_time(getNow()); // 请假对应类型表中为2
			approval.setA_type(a_type.getApprovalType()); 
			// 插入审批信息并返回审批号
			return utilApprovalService.addApprovalGetId(approval);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApprovalException(e);
		}
		
	}

	/**
	 * 向关系表插入关系的方法
	 * @param table_key 插入加班、申领、申购、通知表后获得的主键
	 * @param a_id	AoorovalUtil.addApprovalGetId()获得的审批号
	 * @param a_type 审批类型，枚举
	 * @return
	 */
	public static void addRelationship(Integer table_key,Integer a_id,ApprovalApplyType a_type) {
		try {
			//交给service判断审批类型
			utilApprovalService.addRelationship(table_key,a_id,a_type.getApprovalType());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApprovalException(e);
		}
		
		
	}

}
